package br.com.aquinoevasconcelos.servlets.cliente;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.aquinoevasconcelos.fachada.Fachada;
import br.com.aquinoevasconcelos.modelos.Endereco;
import br.com.aquinoevasconcelos.user.UsuarioCliente;
import br.com.aquinoevasconcelos.util.Pastas;

/**
 * Servlet implementation class InserirCliente
 */
@WebServlet("/InserirCliente")
public class InserirCliente extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public InserirCliente() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Fachada fachada = Fachada.getInstancia();
		UsuarioCliente cliente = new UsuarioCliente();
		Endereco endereco = new Endereco();

		endereco.setBairro(request.getParameter("bairro"));
		endereco.setCep(request.getParameter("cep"));
		endereco.setCidade(request.getParameter("cidade"));
		endereco.setComplemento(request.getParameter("complemento"));
		endereco.setEstado(request.getParameter("estado"));
		endereco.setRua(request.getParameter("rua"));

		cliente.setNome(request.getParameter("nome"));
		cliente.setRazaoSocial(request.getParameter("razao_social"));
		cliente.setNomeFantasia(request.getParameter("nome_fantasia"));
		cliente.setCnpj(request.getParameter("cnpj"));
		cliente.setEmail(request.getParameter("email"));
		cliente.setLogin(request.getParameter("login"));
		cliente.setSenha(request.getParameter("senha"));

		cliente.setTributacao(request.getParameter("tributacao"));

		cliente.setInscricaoEstadual(request.getParameter("inscricaoEstadual"));

		cliente.setInscricaoMunicipal(request
				.getParameter("inscricaoMunicipal"));

		cliente.setEndereco(endereco);

		try {

			if (fachada.validaLogin(request.getParameter("login")) == true) {

				request.setAttribute("cacheCliente", cliente);
				request.getRequestDispatcher("admin/novo_cliente.jsp").forward(request, response);
			}

			else {

				fachada.inserirCliente(cliente);
				new Pastas().criarPastaClienteLinux(request
						.getParameter("nome"));
				response.sendRedirect("admin/novo_cliente.jsp?msg=sucesso");
			}

		} catch (Exception e) {

			RequestDispatcher rd = request.getRequestDispatcher("../erro.jsp");
			rd.forward(request, response);
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		service(request, response);
	}

}
